<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NFlex,
  NSelect,
  NTree,
  NTreeSelect,
  useMessage,
  NButton,
  NUpload,
  NImage,
  NSwitch,
  NAvatar, NSpace,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import { getToken } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import { useRoute } from 'vue-router'
import { TRUE } from 'sass'
import { router } from '@/router'
const route = useRoute()
import { format } from 'date-fns'
import { useTagsStore } from '@/store'
const tagsStore = useTagsStore()


defineOptions({ name: '门店编辑' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
  handleSave,
} = useCRUD({
  name: '门店编辑',
  initForm: {
    start:"09:00",
    end:"18:00"
  },
  doCreate: api.createSettingSpace,
  doUpdate: api.updateSettingSpace,
  doDelete: api.deleteSettingSpace,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  token: getToken(),
  uploadAction: base_path + 'api/appointment/space/file',
  TypeData: [
    {
      label: '实体',
      value: 1,
    },
    {
      label: '虚拟',
      value: 2,
    },
  ],
  CityData: [],
  tag_options: [
    {
      label: '推荐',
      value: '推荐',
    },
    {
      label: '加精',
      value: '加精',
    },
  ],
  parentData: [],
  gotypeData: [
    {
      label: '无跳转',
      value: 0,
    },
    {
      label: '跳转文章',
      value: 1,
    },
  ],
  project_roles_options:[],
  fileList: [],
  upload: null,
  fileListLength: 0,
  dateOptions: [],
})


function on_save() {
  handleSave()
}

async function get_data(id) {
  let ret = await api.getSettingSpaceById({ data_id: id })
  data.row = ret.data
  handleEdit(data.row)
  data.fileList.value = [
    {
      id: 1,
      name: '封面',
      url: data.row.picture,
      status: 'finished',
    },
  ]
}
function on_list() {
  tagsStore.removeTag(route.fullPath)
  router.push('/appointment/settings/space')
}

onMounted(() => {
  const id = route.query.id
  modalVisible.value = true
  if (id > 0) {
    get_data(id)
  } else {
    handleAdd()
  }
  api.getSettingCity().then((res) => (console.log(res.data)))
  api.getSettingProjectTree().then((res) => (data.project_roles_options = res.data))
  $table.value?.handleSearch()
})

watch(modalVisible, (newValue, oldValue) => {
  if (!modalVisible.value) {
    tagsStore.removeTag(route.fullPath)
    router.push('/appointment/settings/space')
  }
})


//上传封面图
//图文信息
const message = useMessage()
const customRequestMethod1 = (options) => {
  console.log(options, 'options')

  const { file } = options.file
  const formData = new FormData()
  formData.append('file', file)
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
    .then((response) => response.json())
    .then((data) => {
      console.log(data, 'datatat')
      if (data.code == 200) {
        modalForm.value.picture = data.data.url
        message.success('封面图上传成功')
        options.onProgress(data)
      } else {
        message.error(data.msg)
      }
    })
}


const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}

//处理多个日期

const today = new Date()
for (let i = 0; i < 30; i++) {
  const date = new Date(today)
  date.setDate(today.getDate() + i)
  data.dateOptions.push({ label: format(date, 'yyyy-MM-dd'), value: format(date, 'yyyy-MM-dd') })
}

const upValuedate = (value) => {
  modalForm.value.date = value
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}

//格式化关联商品选中
function flattenTree(list) {
  const result = []
  function flatten(_list = []) {
    _list.forEach((item) => {
      result.push(item)
      flatten(item.children)
    })
  }
  flatten(list)
  return result
}
const renderSourceList = function ({ onCheck, pattern }) {
  return h(NTree, {
    style: 'margin: 0 4px;',
    keyField: 'value',
    checkable: true,
    selectable: true,
    blockLine: true,
    checkOnClick: true,
    cascade: true,
    data: data.project_roles_options,
    pattern,
    checkedKeys: modalForm.project_roles,
    onUpdateCheckedKeys: (checkedKeys) => {
      onCheck(checkedKeys)
    },
  })
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="编辑门店">
    <NForm
      ref="modalFormRef"
      label-placement="left"
      label-align="left"
      :label-width="150"
      :model="modalForm"
      size="large"
      :rules="validateAddUser"
    >
      <n-card content-style="padding: 0;">
        <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
          <n-tab-pane name="基础信息">
            <NFormItem label="名称" path="name">
                <NInput
                  v-model:value="modalForm.name"
                  clearable
                  placeholder="请输入名称"
                />
              </NFormItem>
              <NFormItem label="英文名称" path="english_name">
                <NInput
                  v-model:value="modalForm.english_name"
                  clearable
                  placeholder="请输入英文名称"
                />
              </NFormItem>
              <NFormItem label="排序" path="sort">
                <NInputNumber
                  v-model:value="modalForm.sort"
                  clearable
                  placeholder="输入排序"
                  :default-value="0"
                />
              </NFormItem>

              <NFormItem label="所属城市" path="city_id">
                <NSelect
                  v-model:value="modalForm.city_id"
                  :options="data.CityData.value"
                  placeholder="请选择所属城市"
                />
              </NFormItem>
              <NFormItem label="门店类型" path="type">
                <NSelect
                  v-model:value="modalForm.type"
                  :options="data.TypeData"
                  placeholder="请选择门店类型"
                />
              </NFormItem>
              <NFormItem label="联系电话" path="phone">
                <NInput v-model:value="modalForm.phone" clearable placeholder="请输入联系电话" />
              </NFormItem>
            <NFormItem label="详细地址" path="address">
                <NInput v-model:value="modalForm.address" clearable placeholder="请输入详细地址" />
              </NFormItem>

            <NFormItem label="经度" path="lat">
                <NInput v-model:value="modalForm.lat" clearable placeholder="请输入经度" />
              </NFormItem>
            <NFormItem label="纬度" path="lon">
                <NInput v-model:value="modalForm.lon" clearable placeholder="请输入纬度" />
              </NFormItem>

              <NFormItem label="简介" path="intro">
                <NInput
                  type="textarea"
                  v-model:value="modalForm.intro"
                  clearable
                  placeholder="请输入备注"
                />
              </NFormItem>

              <NFormItem label="封面图" path="picture">
                <NUpload
                  :action="data.uploadAction"
                  :headers="{ token: data.token }"
                  :max="1"
                  :custom-request="customRequestMethod1"
                  list-type="image-card"
                  v-model:file-list="data.fileList.value"
                  :show-file-list="true"
                >
                </NUpload>
              </NFormItem>

              <NFormItem label="详情组图" path="images" style="width: 100%">
                <NUpload
                  :action="data.uploadAction"
                  :headers="{ token: data.token }"
                  multiple
                  list-type="image-card"
                  @finish="handleFinish"
                  v-model:file-list="modalForm.images"
                >
                </NUpload>
              </NFormItem>
              <NFormItem label="图文介绍" path="content_pic" style="width: 100%">
                <NUpload
                  :action="data.uploadAction"
                  :headers="{ token: data.token }"
                  multiple
                  list-type="image-card"
                  @finish="handleFinish"
                  v-model:file-list="modalForm.content_pic"
                >
                </NUpload>
              </NFormItem>

          </n-tab-pane>
          <n-tab-pane name="预约配置">
<!--              <NFormItem label="可预约日期" path="date">-->
<!--                <n-space align="center">-->
<!--                  <n-select-->
<!--                    v-model:value="modalForm.date"-->
<!--                    :options="data.dateOptions"-->
<!--                    multiple-->
<!--                    placeholder="选择多个日期"-->
<!--                    @update-value="upValuedate"-->
<!--                    style="width: 800px"-->
<!--                  />-->
<!--                </n-space>-->
<!--              </NFormItem>-->

              <NFormItem label="时间间隔" path="interval">
                <NInputNumber
                  v-model:value="modalForm.interval"
                  clearable
                  placeholder="输入时间"
                  :default-value="30"
                />
              </NFormItem>
            <NFormItem label="营业开始时间" path="start">
                <n-time-picker
                  v-model:formatted-value="modalForm.start"
                  value-format="HH:mm"
                />
              </NFormItem>
              <NFormItem label="营业结束时间" path="end">
                <n-time-picker
                  v-model:formatted-value="modalForm.end"
                  value-format="HH:mm"
                />
              </NFormItem>

<!--              <NFormItem label="停车信息填写" path="parking_on">-->
<!--                <NSwitch-->
<!--                  v-model:value="modalForm.parking_on"-->
<!--                  :checked-value="true"-->
<!--                  :unchecked-value="false"-->
<!--                  :default-value="false"-->
<!--                  ><template #checked>开启</template><template #unchecked>关闭</template>-->
<!--                </NSwitch>-->
<!--              </NFormItem>-->
<!--              <NFormItem label="停车费 元/小时" path="parking_cost">-->
<!--                <NInputNumber-->
<!--                  v-model:value="modalForm.parking_cost"-->
<!--                  clearable-->
<!--                  placeholder="输入停车费"-->
<!--                  :default-value="0"-->
<!--                />-->
<!--              </NFormItem>-->

          </n-tab-pane>

          <n-tab-pane name="项目配置">

            <NFormItem label="项目配置" path="project_roles">
              <n-transfer
                v-model:value="modalForm.project_roles"
                :options="flattenTree(data.project_roles_options)"
                :render-source-list="renderSourceList"
                source-filterable
              />
            </NFormItem>
          </n-tab-pane>
        </n-tabs>
      </n-card>
      <n-button :loading="loading" mt-20 type="primary" @click="on_list">返回列表</n-button>
      <n-button :loading="loading" mt-20 ml-15 type="primary" @click="on_save">保存</n-button>
    </NForm>
  </CommonPage>
</template>
